package com.edu.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.edu.entity.GoodsToWeb;
import com.edu.entity.Tool;
import com.edu.entity.User;
import com.edu.entity.address;
import com.edu.service.impl.GoodServerImpl;
import com.edu.service.impl.UserServerImpl;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * Servlet implementation class buyGoodsServlet
 */
@WebServlet(name = "buyGoods", urlPatterns = { "/buyGoods" })
public class buyGoodsServlet extends HttpServlet {
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		UserServerImpl usi = new UserServerImpl();
		GoodServerImpl gsi = new GoodServerImpl();
		
		ObjectMapper om = new ObjectMapper();
		HttpSession session = request.getSession();
		GoodsToWeb gtw = (GoodsToWeb) session.getAttribute("good");
		User u = (User) session.getAttribute("logInUser");
		System.out.println(gtw.getGoodTradetType());
		System.out.println(gtw.getGoodFreightType());
		ArrayList<address> addressList = usi.findAddress(u);
		System.out.println("查到地址数："+addressList.size());
		request.setAttribute("address", addressList);
		request.setAttribute("buyer", u);
		request.setAttribute("goods", gtw);
		request.getRequestDispatcher("buyGoods.jsp").forward(request, response);
	}
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		request.setCharacterEncoding("UTF-8");
		response.setCharacterEncoding("UTF-8");
		ObjectMapper om = new ObjectMapper();
		System.out.println("卖家："+request.getParameter("address1"));
		System.out.println("买家："+request.getParameter("address2"));
		String sellerAddress = request.getParameter("address1").substring(0,2);
		String buyerAddress = request.getParameter("address2").substring(0,2);
		Tool t1 = new Tool();
		double fee = t1.feeCount(sellerAddress, buyerAddress);
		String json = om.writeValueAsString(fee);
		PrintWriter pw = response.getWriter();
		pw.print(json);
		pw.flush();
		// 根据地址更新运费，已完成双方的地址传入后端
	}

}
